<?php
require_once 'lib/libs.php';
session_start ();

$usuario = 'guest';
$smarty = getSmarty ();

if (array_key_exists ( 'USR', $_SESSION )) {
	$usr = $_SESSION ['USR'];
	$usuario = $usr;
}

// public $id;
// public $apellido;
// public $password;//password hash
// public $nombre;
// public $email;
// public $alta;
// public $activo ='N';
// public $comentarios=0;
// public $baja ='N';
// public $motivo_baja ='';
// public $recibe_mail ='S';
// public $creditos=0;
// public $dni;

$op = 'nuevo';

if (isset ( $_REQUEST ['op'] )) {
	$op = $_REQUEST ['op'];
	if (isset ( $_REQUEST ['web'] )) {
		$web = $_REQUEST ['web'];
	}
	if ($op == 'alta') {
		$usr = new Usuario ();
		$usr->setNombre ( $_REQUEST ['nombre'] );
		$usr->setApellido ( $_REQUEST ['apellido'] );
		$usr->setEmail ( $_REQUEST ['correo'] );
		$usr->setDni ( $_REQUEST ['dni'] );
		$pass = '';
		if ($web == 'no') {
			$pass = trim ( strtolower ( $_REQUEST ['nombre'] ) );
		} else {
			$pass = $_REQUEST ['clave'];
		}
		
		$usr->setPassword ( md5 ( $pass ) );
		$usr->setAlta ( time () );
		$usr->setTelefono ( $_REQUEST ['telefono'] );
		$usr->setLibre ( 'N' );
		$usr = DAOUsuario::add ( $usr );
		echo json_encode ( $usr );
		return;
	}
	if ($op == 'edicion') {
		$id = $_REQUEST ['id'];
		$usr = DAOUsuario::getById ( $id );
		$smarty->assign ( 'usr', $usr );
		$smarty->assign ( 'web', 'no' );
		$smarty->display ( 'usuarioModal.html' );
		return;
	}
	if ($op == 'update') {
		$usr = DAOUsuario::getById ( $_REQUEST ['idUsuario'] );
		$usr->setNombre ( $_REQUEST ['nombre'] );
		$usr->setApellido ( $_REQUEST ['apellido'] );
		$usr->setEmail ( $_REQUEST ['correo'] );
		$usr->setDni ( $_REQUEST ['dni'] );
		if ($_REQUEST ['certificado'] == 'true') {
			$usr->setCertificado ( 'S');
		} else {
			$usr->setCertificado ( 'N' );
		}
		
		$fechaCertificado =  DateTime::createFromFormat("d/m/Y", $_REQUEST ['fechaCertificado'])->getTimestamp();
		$vencimientoDate = strtotime ( '+ 1 year', $fechaCertificado);
		$usr->setVencimientoCertificado ( DateUtils::getMysqlDate ( $vencimientoDate) );
		$usr->setTelefono ( $_REQUEST ['telefono'] );
		$usr->setPassword ( md5 ( strtolower ( $_REQUEST ['nombre'] ) ) );
		DAOUsuario::update ( $usr );
		$usr = DAOUsuario::getById ( $usr->getId() );
		
		echo json_encode($usr);
		return;
	}
}

$seccion = 'registro';

$smarty->assign ( 'op', $op );
$smarty->assign ( 'web', 'si' );
$smarty->assign ( 'usuario', $usuario );
$smarty->assign ( 'siteTitle', 'Boss Crossfit' );
$smarty->assign ( 'seccion', $seccion );

$smarty->display ( 'index.html' );
?>